package com.ymm.lulutong.domain.utils;

import com.ymm.lulutong.constant.ResultCodeEnum;
import com.ymm.lulutong.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.nio.file.Files;

/**
 * 上传文件路径处理
 *
 * @author guorui
 */
@Slf4j
public class UploadFileUtils {
    public static Result<Boolean> upload(MultipartFile file, String relativePath) {
        try {
            String rootPath = getPath();
            String targetPath = rootPath + "/target/classes/static";
            String storePath = rootPath + "/src/main/resources/static";
            String relativeDir = relativePath.substring(0, relativePath.lastIndexOf('/') + 1);
            File targetDirFile = new File(targetPath + relativeDir);
            File storeDirFile = new File(storePath + relativeDir);
            if (!targetDirFile.exists() && !targetDirFile.mkdirs()) {
                log.error("文件夹创建失败！");
                return Result.fail(false, ResultCodeEnum.FAIL);
            }
            if (!storeDirFile.exists() && !storeDirFile.mkdirs()) {
                log.error("文件夹创建失败！");
                return Result.fail(false, ResultCodeEnum.FAIL);
            }
            File targetFile = new File(targetPath + relativePath);
            File storeFile = new File(storePath + relativePath);
            file.transferTo(targetFile);
            copyFileByStream(targetFile, storeFile);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail(false, ResultCodeEnum.FAIL.getCode(), "文件上传错误");
        }
        return Result.success(true);
    }

    private static String getPath() throws FileNotFoundException {
        String path = ResourceUtils.getURL("classpath:").getPath();
        if (path.charAt(2) == ':') {
            //windows系统
            path = path.substring(1);
        }
        //去掉/target/classes
        int index = path.indexOf("/target");
        return path.substring(0, index);
    }

    private static void copyFileByStream(File file, File fileTo) throws IOException {
        System.out.println("复制文件到");
        Files.copy(file.toPath(), fileTo.toPath());
    }


}
